package com.lcc.forum.demos.web.controller;

import com.lcc.forum.demos.web.common.AppResult;
import com.lcc.forum.demos.web.common.ResultCode;
import com.lcc.forum.demos.web.config.AppConfig;
import com.lcc.forum.demos.web.model.Article;
import com.lcc.forum.demos.web.model.Board;
import com.lcc.forum.demos.web.model.User;
import com.lcc.forum.demos.web.services.IArticleService;
import com.lcc.forum.demos.web.services.IBoradService;
import com.lcc.forum.demos.web.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "文章接口")
@RestController
@Slf4j
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IBoradService boradService;
    @Resource
    private IArticleService articleService;
    @Resource
    private IUserService userService;

    /**
     * 发布新帖子
     * @param request 用于获取当前登录用户
     * @param boardId 版块id
     * @param title 文章标题
     * @param content 文章内容
     * @return
     */
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request, @ApiParam("版块id") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content){
        //1.进行参数校验
        //2.判断用户是否被禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1){
            //用户处于禁言状态
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //3.校验版块是否存在
        Board board = boradService.selectById(boardId.longValue());
        if (board == null || board.getState() == 1 || board.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            //返回响应
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        //4.封装文章对象
        Article article = new Article();
        article.setBoardId(boardId);//版块id
        article.setTitle(title);//文章标题
        article.setContent(content);//文章内容
        article.setUserId(user.getId());//用户id
        //调用service写入代码
        articleService.create(article);
        //操作成功，返回结果
        return AppResult.success();
    }
    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> selectAllByBoardId(@ApiParam("版块id") @RequestParam(value = "boardId",required = false) Long boardId){
        List<Article> articles = null;
        if (boardId == null){
            //查询所有
            articles = articleService.selectAll();
        }else {
            //查询特定版块列表
           articles = articleService.selectAllByBoardId(boardId);
        }
        //判断集合是否为空
        if (articles == null){
            //为空则创建一个空集合传给结果
            articles = new ArrayList<>();
        }
        //响应结果
        return AppResult.success(articles);
    }

    @ApiOperation("根据帖子Id获取详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request, @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id){
        //1.进行参数校验
        //2.获取当前登录的用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //3..使用service
        Article article = articleService.selectDetailById(id);
        //4.判断结果是否为空
        if (article == null){
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断当前登录用户是否为帖子作者
        if (user.getId() == article.getUserId()){
            article.setOwn(true);
        }
        //返回结果
        return AppResult.success(article);
    }

    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子内容") @RequestParam("content") @NonNull String content){
        //需要获取当前登录用户，判断是否处于禁言状态，判断是否是该帖子的作者，只有作者才能进行修改，所以需要从当前session中获取登录用户，并获取当前帖子
        //1.校验参数的有效性
        //2.获取当前登录用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1){//用户被禁言
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //3.获取当前帖子信息，判断当前帖子是否有效
        Article article = articleService.selectById(id);
        if(article == null){
            //返回错误信息--帖子不存在
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //4.判断当前登录用户是否和帖子作者一致
        if (user.getId() != article.getUserId()){
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //5.判断帖子的状态
        if (article.getState() == 1 || article.getDeleteState() == 1){
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //6.调用service
        articleService.modify(id,title,content);
        //7.打印日志
        log.info("帖子更新成功，Aticle id = " + article.getId() + ",User id = " + user.getId() + ".");
        return AppResult.success();
    }

    /**
     * 点赞操作
     * @param id
     */
    @ApiOperation("点赞帖子")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,@ApiParam("帖子Id") @RequestParam("id") @NonNull Long id){
        //校验登录用户是否被禁言
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1){
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //校验帖子是否存在
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if (article.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //调用Service
        articleService.thumbsUpById(id);
        //返回结果
        return AppResult.success();
    }
    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request, @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        //1.参数校验
        //2.校验帖子状态
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() ==1){
            //帖子已删除
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //3.判断当前登录用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断当前用户是否禁言
        if (user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //判断当前登录用户是否是帖子作者
        if (user.getId() != article.getUserId()){
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //调用SERVICE
        articleService.deleteById(id);
        //删除成功，打印日志
        log.info("删除帖子成功，user id =" + article.getUserId() + ", boardId = " + article.getBoardId() + ".");
        //返回操作成功
        return AppResult.success();
    }
    @ApiOperation("根据用户Id获取帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                    @ApiParam("用户Id") @RequestParam(value = "userId",required = false) Long userId){
        //进行参数校验
        //判断是否传入userId
        if (userId == null){
            //未传入userId,获取当前登录用户的帖子列表
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);
    }
}
